import axios from 'axios';
// 创建 axios 实例
const axiosobject = axios.create({
  baseURL: window.server_url,
    timeout: 500000,
    // headers: { 
    //   'Content-Type': 'application/json;charset=utf-8' 
    // }
});
axiosobject.interceptors.request.use(
  (config) => {
    if (!config.headers) {
      throw new Error(
        `Expected 'axios config' and 'axios config.headers' not to be undefined`
      );
    }
    if (config.auth=='true') {
      let token_value=global["vapp"].config.globalProperties.$apis.axios_token()
      if(token_value){
        config.headers.Authorization = token_value;
      }
      delete config.auth
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);
axiosobject.interceptors.response.use(
  (response)=> {
    // if(response.status==200 ){
    // }
    return response.data;
  },
  (error)=> {
    let {response}=error
    if(response){
      if(response.status==401){
        return response.data;
      }
      else if(response.status==500){
        return {
          status:false,
          message:"网络500错误"
        };
      }
    }
    return Promise.reject(error);
  }
);
async function axios_get(url, qs = {}, auth = false, onlyresult = true, timeout=0){
  let config={ 
    params: qs,
    timeout: timeout
  }
  if(auth==true){config.auth='true'}
  return await axios_main(url,null,config,"get",onlyresult)
}
async function axios_main(url, qs, config, type = "get", onlyresult = true){
  let databack=undefined
  try{
    if(type=="get"){
      databack=await axiosobject.get(url,config)
    }
    else if(type=="post"){
      databack=await axiosobject.post(url,qs,config)
    }
    if (typeof databack==="string"){
      return databack;
    }
    else{
      const { status, message, result, location } = databack;
      if (status) {
        if (onlyresult) {
          return result;
        }
      }
      else {
        if (onlyresult) {
          return undefined;
        }
      }
      return databack
    }
  }
  catch(error){
    // console.log(error)
  }
}
async function axios_post(url, qs = {}, auth = false, onlyresult = true, timeout = 0){
  let config={
    timeout: timeout
  }
  if(auth==true){config.auth='true'}
  return await axios_main(url,qs,config,"post",onlyresult) 
}
export function axios_set(){
  global["vapp"].config.globalProperties.$axiosobject = axiosobject
  global["vapp"].config.globalProperties.$axios_get =axios_get
  global["vapp"].config.globalProperties.$axios_post =axios_post
}